package com.szcinda.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.szcinda.controller.configuration.UserLoginToken;
import com.szcinda.repository.BankInfo;
import com.szcinda.service.dto.bankInfo.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@RestController
@RequestMapping("bankInfo")
public class BankInfoController {

    private final BankInfoService bankInfoService;

    public BankInfoController(BankInfoService bankInfoService) {
        this.bankInfoService = bankInfoService;
    }


    @UserLoginToken
    @PostMapping("create")
    @OperationLogAnnotation(operDesc = "创建收款银行信息", operModel = "收款银行信息维护")
    public Result<String> create(@RequestBody BankInfoCreateDto createDto) {
        bankInfoService.create(createDto);
        return Result.success();
    }

    @GetMapping("delete/{id}/{userId}")
    @OperationLogAnnotation(operDesc = "删除收款银行信息", operModel = "收款银行信息维护")
    public Result<String> del(@PathVariable String id, @PathVariable String userId) {
        bankInfoService.delete(id, userId);
        return Result.success();
    }

    @UserLoginToken
    @PostMapping("query")
    public Result<List<BankInfo>> query(@RequestBody BankInfoQueryDto queryDto) {
        return Result.success(bankInfoService.query(queryDto));
    }


    @PostMapping("/import/{opId}/{organizationId}")
    @OperationLogAnnotation(operDesc = "导入收款银行信息", operModel = "收款银行信息维护")
    public Result<String> orderImport(@RequestParam("file") MultipartFile file, @PathVariable String opId, @PathVariable String organizationId) throws Exception {
        InputStream inputStream = file.getInputStream();
        try {
            BankInfoExcelListener listener = new BankInfoExcelListener();
            EasyExcelFactory.readBySax(inputStream, new Sheet(1, 2, BankInfoImportDto.class), listener);
            bankInfoService.batchCreate(listener.getImportDatas(), opId, organizationId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
